package com.test.down;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.download.manager.M3u8DownLoadManager;
import com.download.manager.M3u8DownLoadService;
import com.download.manager.beans.LoadTaskBean;
import com.download.manager.interfaces.OnDownLoadTaskCallBack;
import com.download.manager.utils.M3u8FileUtil;
import com.test.down.beans.LiveBean;
import com.test.down.utils.DownLoadInfouTIL;
import com.test.down.utils.GlidRoundUtils;
import com.test.down.utils.NetTools;

import java.io.IOException;
import java.text.DecimalFormat;

public class M3u8DownLoadView extends LinearLayout {

    private ImageView image_play;
    private TextView title;
    private TextView content;
    private ImageView image_delete;
    private ImageView iv_state;
    private TextView tv_progress;
    private TextView tv_duration;
    private ProgressBar progressBar;
    private boolean showEdit;
    private LiveBean mediaInfo;

    private double videoDuration;
    private Handler mHandler=new Handler();
    private DecimalFormat decimalFormat=new DecimalFormat("0");
    private DecimalFormat progressFormat=new DecimalFormat("0.00");
    private int load_state=-1;//0,下载完成 ，1 下载中，2 暂停中，-1 还未获取到状态,3 等待结束
    private String loadDuration="0";
    private String loadProgress="0";

    private boolean hasLoadFinish=false;

    private String playUrl;

    public M3u8DownLoadView(Context context) {
        super(context);
        initViewBase(context);
    }

    public M3u8DownLoadView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initViewBase(context);
    }

    public M3u8DownLoadView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initViewBase(context);
    }

    private void initViewBase(Context context){
        LayoutInflater.from(context).inflate(R.layout.jl_layout_video_record, this);
        image_play = findViewById(R.id.iv_vr_cover);
        title = findViewById(R.id.tv_vr_title);
        content = findViewById(R.id.tv_vr_summary);
        image_delete = findViewById(R.id.image_delete);
        iv_state = findViewById(R.id.iv_state);
        tv_duration = findViewById(R.id.tv_duration);
        tv_progress = findViewById(R.id.tv_progress);
        progressBar = findViewById(R.id.pb_loading);
    }

    public void initMediaInfo(final LiveBean info){
        playUrl=info.playUrl;
        hasLoadFinish=false;
        initViewData(info);
        if(!checkFileHasLoadAll()){
            checkDownLoadState();
        }

        M3u8DownLoadManager.getInstance().setDownLoadTaskCallBack(playUrl, onChildTaskCallBackInfo);
        iv_state.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                onClickAction();
            }
        });
        this.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                onClickAction();
            }
        });
        this.setOnLongClickListener(new OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                playLocateVideo();
                return false;
            }
        });
        initLoadBaseInfo();
    }

    public void initViewData(final LiveBean info){
        this.mediaInfo=info;
        Glide.with(getContext()).load(mediaInfo.liveCover).placeholder(R.drawable.jl_default_bg)
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .transform(new CenterCrop(getContext()), new GlidRoundUtils(getContext()))
                .diskCacheStrategy(DiskCacheStrategy.SOURCE).into(image_play);
        title.setText(mediaInfo.title);

        if (showEdit) {
            image_delete.setVisibility(View.VISIBLE);
        } else {
            image_delete.setVisibility(View.GONE);
        }

    }

    private Runnable loadingStateChange=new Runnable() {
        @Override
        public void run() {
            if(hasLoadFinish) return;
            if(load_state!=1){
                load_state=1;
                iv_state.setImageResource(R.mipmap.downloadpause);
            }
            if(progressBar.getVisibility()== View.GONE){
                progressBar.setVisibility(VISIBLE);
            }
            int p= Integer.parseInt(loadProgress);
            int d= Integer.parseInt(loadDuration);
            if(d==0) {
                tv_progress.setText("未知大小");
                progressBar.setMax(10*p+1);
                progressBar.setProgress(p);
            }else {
                tv_progress.setText(progressFormat.format(p * 100.0 / d) + "%");
                progressBar.setMax(d);
                progressBar.setProgress(p);
            }
//            tv_progress.setText(tv_progress.getText()+"  "+loadProgress+" / "+loadDuration);
        }
    };

    private Runnable finishLoad=new Runnable() {
        @Override
        public void run() {
            M3u8DownLoadManager.getInstance().removeDownLoadTaskCallBack(playUrl);
            load_state=0;
            iv_state.setImageResource(R.mipmap.downloadfinish);
            progressBar.setVisibility(GONE);
            String result=M3u8FileUtil.getCacheM3u8Size(M3u8DownLoadManager.getInstance().SAVE_DIRS,playUrl);
            tv_progress.setText(result);
        }
    };

    private Runnable onError=new Runnable() {
        @Override
        public void run() {
            changeLoadState(2);
            M3u8DownLoadManager.getInstance().pauseOrStopTask(playUrl);
            M3u8DownLoadManager.getInstance().removeDownLoadTaskCallBack(playUrl);
            progressBar.setVisibility(GONE);
            iv_state.setImageResource(R.mipmap.downloading);
            String result=M3u8FileUtil.getCacheM3u8Size(M3u8DownLoadManager.getInstance().SAVE_DIRS,
                    playUrl);
            tv_progress.setText("下载失败"+"已缓存:"+result);
        }
    };

    public void setOnDeleteItemListener(final OnClickListener clickListener){
        image_delete.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                M3u8DownLoadManager.getInstance().pauseOrStopTask(playUrl);
                DownLoadInfouTIL.getInstance().deleteItemInDownLoadList(mediaInfo);
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        M3u8FileUtil.deleteCacheFile(M3u8DownLoadManager.getInstance().SAVE_DIRS,
                                playUrl);
                    }
                },2000);
                clickListener.onClick(v);
            }
        });
    }

    /**
     * 切换修改状态
     * @param showEdit
     */
    public void setShowEdit(boolean showEdit) {
        this.showEdit = showEdit;
        if (showEdit) {
            image_delete.setVisibility(View.VISIBLE);
        } else {
            image_delete.setVisibility(View.GONE);
        }
    }

    private void logMsg(String key, String value){
        Log.d(key,value);
    }

    /**
     * 校验文件是否已下载完整
     */
    private boolean checkFileHasLoadAll(){
        try {
            boolean integrity = M3u8FileUtil.checkFileIntegrity(M3u8DownLoadManager.getInstance().SAVE_DIRS, playUrl);
            if (integrity) {
                hasLoadFinish=true;
                load_state=0;
                progressBar.setVisibility(GONE);
                iv_state.setVisibility(View.VISIBLE);
                iv_state.setImageResource(R.mipmap.downloadfinish);
                String result=M3u8FileUtil.getCacheM3u8Size(playUrl);
                tv_progress.setText(result);
            } else {
                iv_state.setVisibility(View.GONE);
            }
            return integrity;
        }catch (IOException e){
            return false;
        }
    }

    private void checkDownLoadState(){
        LoadTaskBean loading=M3u8DownLoadManager.getInstance().getLoadUrlInfo(playUrl);
        if(loading==null) {
            //不再下载列表中
            String result= M3u8FileUtil.getCacheM3u8Size(playUrl);
            tv_progress.setText(result);
        }else {
            //待下载或者正在下载
            if(loading.stateCode==0) {
                tv_progress.setText(loading.state);
            }
        }
        load_state = 2;
        iv_state.setVisibility(View.VISIBLE);
        iv_state.setImageResource(R.mipmap.downloading);
        progressBar.setVisibility(GONE);
    }

    private void changeLoadState(int state){
        load_state=state;
        if(load_state==0){
            iv_state.setImageResource(R.mipmap.downloadfinish);
        }else if(load_state==1){
            iv_state.setImageResource(R.mipmap.downloadpause);
        }else if(load_state==2){
            iv_state.setImageResource(R.mipmap.downloading);
        }else if(load_state==3){
            progressBar.setVisibility(GONE);
            iv_state.setImageResource(R.mipmap.downloading);
            tv_progress.setText("正在暂停下载...");
        }
    }

    private void playLocateVideo(){
        try {
            Intent intent = new Intent();
            intent.setClass(getContext(), FullVideoActivity.class);
            intent.putExtra("path", M3u8FileUtil.getLocateSavePlayFile(M3u8DownLoadManager.getInstance().SAVE_DIRS, playUrl));
            intent.putExtra("title", mediaInfo.title);
            getContext().startActivity(intent);
        }catch (Exception e){
            Toast.makeText(getContext(),"打开视频失败,请稍后再试", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * item 以及图标点击操作时间
     */
    private void onClickAction(){
        if(load_state==-1 || load_state==3) return;
        if(load_state==0){
            //播放
            playLocateVideo();
        }else if(load_state==1){
            //停止下载
            changeLoadState(3);
            M3u8DownLoadManager.getInstance().pauseOrStopTask(playUrl);
        }else if(load_state==2){
            if(NetTools.getInstance().isNetworkAvailable((Activity)getContext())) {
                //开始下载
                M3u8DownLoadManager.getInstance().setDownLoadTaskCallBack(playUrl, onChildTaskCallBackInfo);
                startDownLoad();
                tv_progress.setText("等待下载");
                changeLoadState(1);
            }else {
                MyApplication.instance.systemToast("当前网络不可用，请稍后再试!");
            }
        }
    }

    private Runnable onPauseRunnable=new Runnable() {
        @Override
        public void run() {
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    progressBar.setVisibility(GONE);
                    changeLoadState(2);
                    String result= M3u8FileUtil.getCacheM3u8Size(playUrl);
                    tv_progress.setText(result);
                }
            },100);
        }
    };

    private Runnable onStartRunnable=new Runnable() {
        @Override
        public void run() {
            initLoadBaseInfo();
        }
    };

    /**
     * 获取预存的下载数据初始化界面
     */
    private void initLoadBaseInfo(){
        try {
            //获取预存的下载数据
            LoadTaskBean pro = M3u8DownLoadManager.getInstance().getLoadUrlInfo(playUrl);
            if (pro!=null) {
                iv_state.setImageResource(R.mipmap.downloadpause);
                if(pro.stateCode==0){
                    tv_progress.setText(pro.state);
                    progressBar.setVisibility(GONE);
                }else {
                    loadProgress = decimalFormat.format(pro.progress);
                    loadDuration = decimalFormat.format(pro.duration);
                    mHandler.post(loadingStateChange);
                }
            }
        }catch (Exception e){}
    }

    private OnDownLoadTaskCallBack onChildTaskCallBackInfo=new OnDownLoadTaskCallBack() {
        @Override
        public void onDuration(String initialUrl, String key, double duration) {
            if(playUrl.equals(key)) {
                videoDuration = duration;
//                logMsg("M3u8DownLoadView", "onDuration " + duration);
            }
        }

        @Override
        public void onLoadProgress(String initialUrl, String key, final double progress, final double duration) {
            if(playUrl.equals(key)) {
                loadDuration=decimalFormat.format(duration);
                loadProgress=decimalFormat.format(progress);
                mHandler.post(loadingStateChange);
//                logMsg("M3u8DownLoadView", "onLoadProgress " + progress);
            }
        }

        @Override
        public void onLoadTsProgress(String initialUrl, String key, int progress, double duration) {
            if(playUrl.equals(key)) {
//                logMsg("M3u8DownLoadView", "onLoadTsProgress " + progress);
            }
        }

        @Override
        public void onLoadTsDuration(String initialUrl, String key, int duration) {
            if(playUrl.equals(key)) {
//                logMsg("M3u8DownLoadView", "onLoadTsDuration " + duration);
            }
        }

        @Override
        public void onCanPlayProgress(String initialUrl, String key, double progress) {
            if(playUrl.equals(key)) {
//                logMsg("M3u8DownLoadView", "onCanPlayProgress " + progress);
            }
        }

        @Override
        public void onM3u8SaveFile(String initialUrl, String key, String fileName, boolean isInitial) {
            if(playUrl.equals(key)) {
                logMsg("M3u8DownLoadView", "onM3u8SaveFile " + fileName);
            }
        }

        @Override
        public void onTSSaveFile(String initialUrl, String key, String fileName) {
            if(playUrl.equals(key)) {
                logMsg("M3u8DownLoadView", "onTSSaveFile " + fileName);
            }
        }

        @Override
        public void onDownLoadFinish(String initialUrl, String key, boolean success) {
            if(playUrl.equals(initialUrl)) {
                hasLoadFinish=true;
                logMsg("M3u8DownLoadView", "onDownLoadFinish " + success);
                if(success) {
                    mHandler.post(finishLoad);
                }else {
                    mHandler.post(onError);
                }
            }
        }

        @Override
        public void onDownLoadError(String initialUrl, String key, boolean success) {
            if(playUrl.equals(initialUrl)) {
                mHandler.post(onError);
            }
        }

        @Override
        public void onPauseDownLoad(String initialUrl, String key) {
            mHandler.post(onPauseRunnable);
        }

        @Override
        public void onStartLoad(String initialUrl, String key) {
            mHandler.post(onStartRunnable);
        }
    };

    private void startDownLoad(){
        Intent intent=new Intent(getContext(), M3u8DownLoadService.class);
        intent.putExtra(M3u8DownLoadService.URL_VALE,playUrl);
        getContext().startService(intent);
    }
}
